<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Http\Requests\Admin\BaseRequest;
use App\Models\Admin\AdminListField;
use App\Models\Admin\AdminOperateModule;
use App\Models\Admin\Company;
use App\Models\Admin\Order;
use App\Models\Admin\OrderList;
use App\Models\Admin\RenewalOrder;
use Saas,Auth,DB;
use Illuminate\Http\Request;
use App\Exports\AllExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
use App\Log\ExportsAdminLog;

class ExportsController extends Controller
{
    use AdminTrait;

    protected $model;
    protected $mode = [
    1 => '采购员',
    2 => '供应商',
    ];
    protected $type = [
    1 => '计划采购',
    2 => '备货采购',
    ];
    protected $pay_status = [
    0 => '未支付',
    1 => '已支付',
    ];
    protected $status = [
    0 => '待采购',
    1 => '部分采购',
    2 => '完成采购',
    3 => '已取消',
    ];
    protected $statusList_return = [
    0 => '待审核',
    1 => '已完成',
    2 => '已取消',
    ];
    protected $typeList_return = [
    1 => '按商品退',
    2 => '按采购单退'
    ];
    public function __construct(OrderList $model)
    {
        $this->model = $model;
    }
     function addLog($pre,$next,$type,$MODEL,$method='',$pid=5)
    {
        $info = AdminOperateModule::where('pid',$pid)->where('type',$type)->where('model',$MODEL)->when($method,function ($query)use ($method){
            $query->where('method',$method);
        })->first();
        if (!empty($info)){
            $adminLog = new ExportsAdminLog($pre,$next,$info);
            $adminLog->addLog();
        }
    }

    /***************************************************                    导出订单管理                             ****************************************************************/
    /**
     * 导出 给前端的默认字段 get
     * Dispatch/export/exports_info
     * @return order 订单表头 order_list订单商品表头
     */
    public function exports_info(Request $request){
        $order= AdminListField::getListField(10);
        $order_list= AdminListField::getListField(11);
        $purchase_list= AdminListField::getListField(12);
        $advice_list= AdminListField::getListField(13);
        $list=[
            'type_10'=>$order,//订单导出表头
            'type_11'=>$order_list,//订单商品导出表头
            'type_12'=>$purchase_list,//采购单商品导出表头
            'type_13'=>$advice_list,//财务单 结算列表 列表导出表头
        ];
        return $this->success(['list'=>$list]);
    }
    /**
     * 导出 订单 post
     * Dispatch/export/exports
     * @param ids string 可选 10-11-12
     * @param send_time 可选 string 2020-10-11 2020-10-12
     * @param companyName 可选 string 测试一
     * @param is_status 必选 int 0 订单导出 1商品导出
     * @param order_head 必选 string  1-2-3  订单导出表头
     * @param list_head 必选 string  1-2-3  订单商品导出表头
     */
    public function exports(Request $request,Order $order){
        $count_order_head=0;
        $count_list_head=0;
        $ids=[];
        $is_status=$request->is_status;
        $send_time='';
        $name='';
        $order_head=[];
        $list_head=[];
        if( $request->ids){
            $ids=$request->ids;
            $ids =explode('-',$ids);
        }
        if( $request->send_time){
            $send_time=$request->send_time;
        }
        if( $request->companyName){
            $name=$request->companyName;
        }
        $data=$order->seachone($send_time,$ids,$name);
        $head=[
            '仓库',
            '订单号',
            '商户名称',
            '下单日期',
            '配送日期',
            '下单金额',
            '配送金额',
            '退货金额',
            '运费',
            '订单状态',
            '支付状态',
            '备注',
            '业务员',
            '司机',
            '路线',
            '来源',
            '子账号',
            '打印',
            '收货人',
            '收货手机',
            '收货地址'
        ];
        $count_order_head=count($head);
        $head_list=[
            'cc',//没有的
            'order_sn',
            'company_name',
            'created_at',
            'delivery_time',
            'order_money',
            'send_money',
            'return_money',
            'delivery_fee',
            'order_status',
            'pay_status',
            'remark',
            'salesman',
            'driver',
            'line',
            'from',
            'zz',//没有的
            'is_print',
            'contact',
            'mobile',
            'address',
        ];

        if($request->order_head){
            $arre=explode('-',$request->order_head);
            $count_order_head=count($arre);
            foreach ($arre as $val){
                $order_head[]=$head_list[$val-1];
            }
            $heads=[];
            foreach ($arre as $val){
                $heads[]=$head[$val-1];
            }
            $head=$heads;
            $order_head=array_diff($head_list,$order_head);
        }

        $arr_list=[
            '商品名称',
            '分类',
            'SKU编码',
            '单位',
            '下单数量',
            '下单单价',
            '下单小计',
            '配送数量',
            '配送单价',
            '配送小计',
            '产地',
            '保质期',
            '生产日期',
            '备注'
        ];

        $arr_list_string=[
            'name',
            'type',
            'code',
            'unit',
            'order_num',
            'order_price',
            'order_all',
            'sort_num',
            'sort_price',
            'sort_all',
            'candi',
            'baozhiqi',
            'mfg',
            'remark',
        ];
        if($request->list_head){
            $arre=explode('-',$request->list_head);
            $count_list_head=count($arre);
            foreach ($arre as $val){
                $list_head[]=$arr_list_string[$val-1];
            }
            $arr_lists=[];
            foreach ($arre as $val){
                $arr_lists[]=$arr_list[$val-1];
            }
            $arr_list=$arr_lists;
            $list_head =array_diff($arr_list_string,$list_head);
        }

        //需要加颜色 的行
        $y_arr=[];
        //需要加高 的行
        $data_info=[];
        $num=0;
        foreach ($data as $val){//订单导出
            if($num==0){
                $y_arr[]=$num;
            }
            $num++;
            if($request->is_status){
                $y_arr[]=$num;
            }

            $data_info[$num]['cc']='';
            $data_info[$num]['order_sn']=$val['order_sn'];
            $data_info[$num]['company_name']=$val['company_name']['company_name'];
            $data_info[$num]['created_at']=date('Y-m-d',$val['created_at']);
            $data_info[$num]['send_time']=date('Y-m-d',$val['send_time']);
            $data_info[$num]['order_money']="\t".$val['order_money'];
            $data_info[$num]['send_money']="\t".$val['send_money'];
            $data_info[$num]['return_money']="\t".$val['return_money'];
            $data_info[$num]['delivery_fee']="\t".$val['delivery_fee'];
            if($val['order_status']==0){
                $data_info[$num]['order_status']='待审核';
            }
            if($val['order_status']==1){
                $data_info[$num]['order_status']='备货中';
            }
            if($val['order_status']==2){
                $data_info[$num]['order_status']='配送中';
            }
            if($val['order_status']==3){
                $data_info[$num]['order_status']='已完成';
            }
            if($val['order_status']==4){
                $data_info[$num]['order_status']='已取消';
            }
            if($val['pay_status']==0){
                $data_info[$num]['pay_status']='未支付';
            }
            if($val['pay_status']==1){
                $data_info[$num]['pay_status']='已支付';
            }
            $data_info[$num]['remark']=$val['remark'];
            $data_info[$num]['salesman']=$val['salesman'];
            $data_info[$num]['driver']=$val['driver'];
            $data_info[$num]['line']=$val['line'];
            if($val['from']==0){
                $data_info[$num]['from']='后台';
            }
            if($val['from']==1){
                $data_info[$num]['from']='公众号';
            }
            if($val['from']==2){
                $data_info[$num]['from']='小程序';
            }
            if($val['from']==3){
                $data_info[$num]['from']='pc';
            }
            if($val['from']==4){
                $data_info[$num]['from']='APP';
            }
            $data_info[$num]['zz']='';
            if($val['is_print']==0){
                $data_info[$num]['is_print']='未打印';
            }
            if($val['is_print']==1){
                $data_info[$num]['is_print']='已打印';
            }
            $data_info[$num]['contact']=$val['contact'];
            $data_info[$num]['mobile']=$val['mobile'];
            $data_info[$num]['address']=$val['address'];
            foreach ($order_head as $vv){
                unset($data_info[$num][$vv]);
            }
            if($is_status==1){//商品导出
                if($val['order_list_info']!=''){
                    $num++;
                    $data_info[$num]=$arr_list;
                }
                foreach ($val['order_list_info'] as $v1){
                    $num++;
                    $data_info[$num]['name']=$v1['name']."【".$v1['spu_name']."】";
                    $data_info[$num]['type']=$v1['goodss']['category_p']['title'].'|'.$v1['goodss']['category']['title'];
                    $data_info[$num]['code']=$v1['goods_spu']['goods_spu_code'];
                    $data_info[$num]['unit']=$v1['unit'];
                    $data_info[$num]['order_num']="\t".$v1['order_num'];
                    $data_info[$num]['order_price']="\t".$v1['order_price'];
                    $o_m=$v1['order_price']*$v1['order_num'];
                    $o_m=bcadd($o_m,0,2);
                    $data_info[$num]['order_all']="\t".$o_m;
                    $data_info[$num]['sort_num']="\t".$v1['sort_num'];
                    $data_info[$num]['sort_price']="\t".$v1['sort_price'];
                    $s_m=$v1['sort_num']*$v1['sort_price'];
                    $s_m=bcadd($s_m,0,2);
                    $data_info[$num]['sort_all']="\t".$s_m;
                    $data_info[$num]['candi']='';
                    $data_info[$num]['baozhiqi']='';
                    $data_info[$num]['mfg']=$v1['mfg'];
                    $data_info[$num]['remark']=$v1['remark'];
                    foreach ($list_head as $vv1){
                        unset($data_info[$num][$vv1]);
                    }
                }
            }
        }
        try {
//            return Excel::download(new OneExport($head,$data_info), 'demo.html');//xlsx //导出单表 array 表头 列表 都是array
            $data = $data_info;//要导入的数据
            $header=$head;
            $he_count=count($header);
            $excel = new AllExport($data,$header,'导出sheetName');
            $abc=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z'];
            $abcs=[];
            $count=0;
            if($count_order_head<=$count_list_head){
                $count=$count_list_head;
            }else{
                $count=$count_order_head;
            }
            $ar_num=0;
            foreach ($abc as $val){
                $ar_num++;
                    $abcs[$val] =15;
            }
            $excel->setColumnWidth($abcs);//设置列宽 "A" => 30, "B" => 30
            $excel->setRowHeight([1 => 50]);//设置行高，$i为数据行数  1 => 50
            $excel->setFont(['A1:U1' => '宋体']);//设置 字体
//            $excel->setFontSize(['A1:I1' => 14,'A2:Z1265' => 14]);//设置 字体大小
            $excel->setBold(['A1:U1' => true]);//设置区域单元格字体粗体 ['A1:Z1' => true]
            $y_arrs=[];
            foreach ($y_arr as $val){
                $val=$val+1;
                $string='A'.$val.':'.$abc[$he_count-1].$val;
                $y_arrs[$string]='E6E6E6';
            };
            $excel->setBackground($y_arrs);//设置区域单元格背景颜色  "A1:Z1" => "E6E6E6"
            //$excel->setMergeCells(['A1:A1']);//合并单元格
//            $excel->setBorders(['A2:D5' => '#000000']);//设置边框颜色
        //日志
            $this->addLog(null,null,7,'dispatch_order','exports',5);
            return Excel::download($excel, '导出文件.xlsx');
        }
        catch (\Exception $e) {
            return [
                'code' => 500,
                'data' => [
                    'err' => 'export_failed',
                    'err_msg' => $e -> getMessage()
                ],
                'msg' => '导出失败'
            ];
        }
//        return $this->success(['list'=>$data]);
    }

    //导出客户列表
    public function exportsCompany(BaseRequest $request)
    {
        $input=$request->all();
        $ids_arr=empty($request->ids)?[]:explode(',',$request->ids);
        $model_list=[1=> '批发', 2 => '城配',3=>'软件'];
        $status_list=[0 => '禁用', 1 => '正常'];
        //$head=['客户名称','负责人','手机号','域名','佣金比例','续费金额','客户类型','所在地','服务开始时间','服务结束时间','服务剩余天数','负责人邮箱','客户公司地址','服务状态'];
        $head=['业务员','客户名称','负责人','手机号','售后','域名','客户类型','佣金比例','续费金额','服务状态','服务开始时间','服务结束时间','剩余天数','客户所在地'];
        if(empty($ids_arr))
        {
            $where=Company::getWhere($input);
            $info=Company::with(['adminRegion','customer'])->where($where)->get()->toArray();
        }
        else
            $info=Company::with(['adminRegion','customer'])->whereIn('id',$ids_arr)->get()->toArray();
        $arr=[];
        $time_now=time();
        foreach ($info as $k =>$val){
            $left_time=$val['end_time']-$time_now;
            $left_time=$left_time<0?0:$left_time;
            $left_time=ceil($left_time/86400);
            $arr[$k]=[
                $val['salesman'],
                $val['company_name'],
                $val['name'],
                $val['mobile'],
                (empty($val['customer'])) ? '' : $val['customer']['name'] ,
                $val['domain_name'],
                $model_list[$val['model']],
                $val['commission_rate'],
                $val['renewal_money'],
                ($val['audit']) ? $status_list[$val['status']] : '待审核',
                date('Y-m-d',$val['start_time']),
                date('Y-m-d',$val['end_time']),
                $left_time.'天',
                substr($val['admin_region']['mername'],7),
                /*$val['email'],
                $val['address'],*/
            ];
        }
        try {
            $excel = new AllExport($arr,$head,'导出客户列表');
            $abc=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z'];
            $abcs=[];
            $numa=0;
            foreach ($abc as $val){
                $numa++;
                $abcs[$val]=15;
            }
            $excel->setColumnWidth($abcs);//设置列宽 "A" => 30, "B" => 30
            $excel->setRowHeight([1 => 30]);//设置行高，$i为数据行数  1 => 50
            $excel->setFont(['A1:Z1265' => '宋体']);//设置 字体
            $excel->setFontSize(['A1:Q1' => 16,'A2:Z1265' => 14]);//设置 字体大小
            $excel->setBold(['A1:N1' => true]);//设置区域单元格字体粗体 ['A1:Z1' => true]
            $excel->setBackground(["A1:N1" => "E6E6E6"]);//设置区域单元格背景颜色  "A1:Z1" => "E6E6E6"
//            $excel->setMergeCells(['A1:I1','A6:I6','B2:C2','B3:C3','B4:C4','B5:C5','D2:E2','D3:E3','D4:E4','D5:E5','F2:I2','F3:I3','F4:I4','F5:I5','B6:I6']);//合并单元格
            //$excel->setBorders(['A2:D5' => '#000000']);//设置边框颜色
//            $this->addLog(0,0,7,'goods','goods',3,5);
            return Excel::download($excel, '导出文件.xlsx');//xlsx
        }
        catch (\Exception $e) {
            $this->error(['-1',$e->getMessage()]);
        }
    }

    //导出报表-客户分析订单
    public function exportsAnalysisList(BaseRequest $request)
    {
        $head=['客户名称','订单数量','下单金额','配送金额','利润金额','利润率'];

        $start_time = $request->star_time ?? date("Y-m-d");
        $end_time = $request->end_time ?? date("Y-m-d");
        $field = $request->field ?? 'send_money';
        $orderBy = $request->orderBy ?? 'desc';

        $list = DB::table('statistics_customer_day')->selectRaw("SUM(order_volume) as order_num,SUM(order_money) as order_money,SUM(amount) as send_money,SUM(cost) as cost_money,SUM(ROUND(amount-cost,2)) as profit_money,IF(SUM(amount) > 0,ROUND((SUM(ROUND(amount-cost,2))/SUM(amount))*100,2),0) as profit_rate,(SELECT company_name FROM ".config('database.connections.mysql.prefix')."company WHERE company_id=id) as company_name,company_id")
            ->whereBetween('timestamps',[strtotime($start_time),strtotime($end_time)])
            ->orderBy($field,$orderBy)->groupBy('company_id')->get();

        $arr=[];
        foreach ($list as $k =>$val){
            $arr[$k]=[
                $val->company_name,
                $val->order_num,
                $val->order_money,
                $val->send_money,
                $val->profit_money,
                $val->profit_rate,
            ];
        }
        try {
            $excel = new AllExport($arr,$head,'客户分析订单表');
            $abc=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z'];
            $abcs=[];
            $numa=0;
            foreach ($abc as $val){
                $numa++;
                $abcs[$val]=15;
            }
            $excel->setColumnWidth($abcs);//设置列宽 "A" => 30, "B" => 30
            $excel->setRowHeight([1 => 30]);//设置行高，$i为数据行数  1 => 50
            $excel->setFont(['A1:Z1265' => '宋体']);//设置 字体
            $excel->setFontSize(['A1:E1' => 16,'A2:Z1265' => 14]);//设置 字体大小
            $excel->setBold(['A1:E1' => true]);//设置区域单元格字体粗体 ['A1:Z1' => true]
            $excel->setBackground(["A1:E1" => "E6E6E6"]);//设置区域单元格背景颜色  "A1:Z1" => "E6E6E6"
            return Excel::download($excel, '导出文件.xlsx');//xlsx
        }
        catch (\Exception $e) {
            $this->error(['-1',$e->getMessage()]);
        }
    }

    public function exportRenewOrder(BaseRequest $request)
    {
        $input=$request->all();
        $ids_arr=empty($request->ids)?[]:explode(',',$request->ids);
        if (empty($ids_arr)) {
            return $this->error(['-1','没有选中任何订单']);
        }
        $head=['订单号','客户','金额','支付时间','创建时间'];
        $list = RenewalOrder::with(['company:id,company_name'])
            ->select('id','company_id','order_sn','money','pay_time','created_at','pay_status')
            ->where('pay_status',1)->whereIn('id',$ids_arr)
            ->orderBy('created_at','desc')->get();
        $arr = [];
        foreach ($list as $k => $v) {
            $arr[$k] = [
                $v->order_sn,
                $v->company->company_name,
                $v->money,
                date("Y-m-d H:i:s",$v->pay_time),
                //date("Y-m-d H:i:s",$v->created_at),
                $v->created_at->format("Y-m-d H:i:s")
            ];
        }
        try {
            $excel = new AllExport($arr,$head,'导出续费订单列表');
            $abc=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','S','Y','Z'];
            $abcs=[];
            $numa=0;
            foreach ($abc as $val){
                $numa++;
                $abcs[$val]=15;
            }
            $excel->setColumnWidth($abcs);//设置列宽 "A" => 30, "B" => 30
            $excel->setRowHeight([1 => 30]);//设置行高，$i为数据行数  1 => 50
            $excel->setFont(['A1:Z1265' => '宋体']);//设置 字体
            $excel->setFontSize(['A1:Q1' => 16,'A2:Z1265' => 14]);//设置 字体大小
            $excel->setBold(['A1:E1' => true]);//设置区域单元格字体粗体 ['A1:Z1' => true]
            $excel->setBackground(["A1:E1" => "E6E6E6"]);//设置区域单元格背景颜色  "A1:Z1" => "E6E6E6"
            return Excel::download($excel, '续费订单.xlsx');
        } catch (\Exception $e) {
            report($e);
            return $this->error(['-1','导出失败']);
        }
    }
}
